﻿using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate.Linq;
using Xenta.Api;
using Xenta.Entities;
using Xenta.Enums;
using Xenta.Security;
using Xenta.Structs;
using Xenta.Utils;

namespace Xenta.Operations
{
    #region __General__

    /// <summary>
    /// Creates a publication.
    /// </summary>
    public class CreatePublication : CreateAuditable<PublicationEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Ctors

        /// <summary>
        /// Initializes a new class instance.
        /// </summary>
        public CreatePublication()
        {
            PublishedOn = DateTime.UtcNow;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("PBLSH");
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .IsVerified()
                    .Rule((ctx, uow) =>
                    {
                        var author = ctx.PublicationAuthor(uow);
                        if(author == null)
                            return false;
                        return author.Flags.HasFlag(PublicationAuthorFlags.Active) &&
                            author.EntityID == AuthorID;
                    });
            }
        }

        /// <summary>
        /// Gets or sets the author identifier.
        /// </summary>
        public int AuthorID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the file group identifier.
        /// </summary>
        public int FileGroupID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the code.
        /// </summary>
        public string Code
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flags.
        /// </summary>
        public PublicationFlags Flags
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the publishing date.
        /// </summary>
        public DateTime PublishedOn
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override Err Validate(IUnitOfWork uow)
        {
            if(String.IsNullOrWhiteSpace(Code))
                return Err.Of<PublicationEntity>().NotValid("Code");
            return base.Validate(uow);
        }

        protected override void Work(IUnitOfWork uow, out PublicationEntity result)
        {
            base.Work(uow, out result);
            uow.Execute(new UpdatePublicationAuthorStats
            {
                EntityID = result.Author.EntityID
            });
        }

        protected override void Construct(IUnitOfWork uow, PublicationEntity entity)
        {
            base.Construct(uow, entity);

            entity.Author = uow.Execute(new GetPublicationAuthor
            {
                ThrowsException = true,
                EntityID = AuthorID
            }).Result;
            entity.FileGroup = FileGroupID != 0 
                ? uow.Execute(new GetFileGroup
                {
                    ThrowsException = true,
                    EntityID = FileGroupID
                }).Result 
                : null;
            entity.Code = Code.TrimToLen(10);
            entity.Flags = Flags;
            entity.PublishedOn = PublishedOn;
        }

        #endregion
    }

    /// <summary>
    /// Updates a publication.
    /// </summary>
    public class UpdatePublication : UpdateAuditable<PublicationEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Ctors

        /// <summary>
        /// Initializes a new class instance.
        /// </summary>
        public UpdatePublication()
        {
            PublishedOn = DateTime.UtcNow;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("PBLSH");
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .IsVerified()
                    .Rule((ctx, uow) =>
                    {
                        var author = ctx.PublicationAuthor(uow);
                        if(author == null || author.EntityID != AuthorID)
                            return false;
                        var publicaiton = uow.Execute(new GetPublication
                        {
                            EntityID = EntityID
                        }).Result;
                        if(publicaiton == null)
                            return false;
                        return publicaiton.Author.EntityID == author.EntityID;
                    });
            }
        }

        /// <summary>
        /// Gets or sets the author identifier.
        /// </summary>
        public int AuthorID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the file group identifier.
        /// </summary>
        public int FileGroupID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the code.
        /// </summary>
        public string Code
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flags.
        /// </summary>
        public PublicationFlags Flags
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the publishing date.
        /// </summary>
        public DateTime PublishedOn
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override Err Validate(IUnitOfWork uow)
        {
            if(String.IsNullOrWhiteSpace(Code))
                return Err.Of<PublicationEntity>().NotValid("Code");
            return base.Validate(uow);
        }

        protected override void Work(IUnitOfWork uow, out PublicationEntity result)
        {
            var oldAuthor = uow.Execute(new GetPublication
            {
                ThrowsException = true,
                EntityID = EntityID
            }).Result.Author;

            base.Work(uow, out result);

            uow.Execute(new UpdatePublicationAuthorStats
            {
                EntityID = result.Author.EntityID
            });
            if(!oldAuthor.Equals(result.Author))
            {
                uow.Execute(new UpdatePublicationAuthorStats
                {
                    EntityID = oldAuthor.EntityID
                });
            }
        }

        protected override void Revise(IUnitOfWork uow, PublicationEntity entity)
        {
            base.Revise(uow, entity);

            entity.Author = uow.Execute(new GetPublicationAuthor
            {
                ThrowsException = true,
                EntityID = AuthorID
            }).Result;
            entity.FileGroup = FileGroupID != 0 
                ? uow.Execute(new GetFileGroup
                {
                    ThrowsException = true,
                    EntityID = FileGroupID
                }).Result 
                : null;
            entity.Code = Code.TrimToLen(10);
            entity.Flags = Flags;
            entity.PublishedOn = PublishedOn;
        }

        #endregion
    }

    /// <summary>
    /// Updates a publication statistics.
    /// </summary>
    public class UpdatePublicationStats : OperateEntityByID<PublicationEntity>
    {
        #region Utilities

        protected override void Work(IUnitOfWork uow, out PublicationEntity result)
        {
            var publication = uow.Execute(new GetPublication
            {
                ThrowsException = true,
                EntityID = EntityID
            }).Result;

            uow.Flush();
            uow.SqlQuery("exec fwk_Publications_UpdateStats @PublicationID=:PublicationID, @UpdatedOn=:UpdatedOn")
                .SetInt32("PublicationID", publication.EntityID)
                .SetDateTime("UpdatedOn", DateTime.UtcNow)
                .ExecuteUpdate();
            uow.Flush();
            
            result = uow.Execute(new RefreshEntity<PublicationEntity>
            {
                Entity = publication
            }).Result;
        }

        #endregion
    }

    /// <summary>
    /// Deletes the publication.
    /// </summary>
    public class DeletePublication : DeleteEntity<PublicationEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("PBLSH");
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .IsVerified()
                    .Rule((ctx, uow) =>
                    {
                        var author = ctx.PublicationAuthor(uow);
                        if(author == null)
                            return false;
                        var publicaiton = uow.Execute(new GetPublication
                        {
                            EntityID = EntityID
                        }).Result;
                        if(publicaiton == null)
                            return false;
                        return publicaiton.Author.EntityID == author.EntityID;
                    });
            }
        }

        /// <summary>
        /// Gets or sets a value indicates, whether 
        /// delete the associated file group.
        /// </summary>
        public bool DeleteFileGroup
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Destruct(IUnitOfWork uow, PublicationEntity entity)
        {
            foreach(var i in entity.Translations)
            {
                uow.Execute(new DeletePublicationTranslation
                {
                    EntityID = i.EntityID
                });
            }
            foreach(var i in entity.Ratings)
            {
                uow.Execute(new DeletePublicationRating
                {
                    EntityID = i.EntityID
                });
            }
            foreach(var i in entity.Comments)
            {
                uow.Execute(new DeletePublicationComment
                {
                    EntityID = i.EntityID
                });
            }
            foreach(var i in entity.Tags.ToList())
            {
                uow.Execute(new UnmapPublicationTagFromPublication
                {
                    EntityID = entity.EntityID,
                    ChildID = i.EntityID
                });
            }
            foreach(var i in entity.Attributes.ToList())
            {
                uow.Execute(new UnmapLookupAttributeFromPublication
                {
                    EntityID = entity.EntityID,
                    ChildID = i.EntityID
                });
            }
            if(DeleteFileGroup && entity.FileGroup != null)
            {
                uow.Execute(new DeleteFileGroup
                {
                    EntityID = entity.FileGroup.EntityID,
                    DeleteFiles = true
                });
            }
            base.Destruct(uow, entity);
        }

        protected override void Work(IUnitOfWork uow)
        {
            var author = uow.Execute(new GetPublication
            {
                ThrowsException = true,
                EntityID = EntityID
            }).Result.Author;

            base.Work(uow);

            uow.Execute(new UpdatePublicationAuthorStats
            {
                EntityID = author.EntityID
            });
        }

        #endregion
    }

    /// <summary>
    /// Gets the publication by identifier.
    /// </summary>
    public class GetPublication : QueryEntityByID<PublicationEntity>,
        IApiOperation
    {
        protected override IQueryable<PublicationEntity> Build(IUnitOfWork uow, IQueryable<PublicationEntity> query)
        {
            query = base.Build(uow, query);
            if(Fetch > FetchLevel.None)
                query = query.Fetch(x => x.Author)
                    .ThenFetch(x => x.Account);
            return query;
        }
    }

    /// <summary>
    /// Gets the publication by code.
    /// </summary>
    public class GetPublicationByCode : QueryEntity<PublicationEntity>,
        IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets or sets the publication code.
        /// </summary>
        public string Code
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override IQueryable<PublicationEntity> Build(IUnitOfWork uow, IQueryable<PublicationEntity> query)
        {
            string code = StringHelper.EnsureNotNull(Code).TrimToLen(10);
            query = base.Build(uow, query);
            query = query.Where(x => x.Code.Equals(code));
            if(Fetch > FetchLevel.None)
                query = query.Fetch(x => x.Author)
                    .ThenFetch(x => x.Account);
            return query;
        }

        #endregion
    }

    #endregion

    #region __Translation__

    /// <summary>
    /// Creates a publication translation.
    /// </summary>
    public class CreatePublicationTranslation : CreateTranslation
        <TPublicationEntity, PublicationEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("PBLSH");
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .IsVerified()
                    .Rule((ctx, uow) =>
                    {
                        var author = ctx.PublicationAuthor(uow);
                        if(author == null)
                            return false;
                        var pub = uow.Execute(new GetPublication
                        {
                            EntityID = HolderID
                        }).Result;
                        if(pub == null)
                            return false;
                        return pub.Author.EntityID == author.EntityID;
                    });
            }
        }

        /// <summary>
        /// Gets or sets the title.
        /// </summary>
        public string Title
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the description.
        /// </summary>
        public string Description
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the text.
        /// </summary>
        public string Text
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Construct(IUnitOfWork uow, TPublicationEntity entity)
        {
            base.Construct(uow, entity);

            entity.Title = StringHelper.EnsureNotNull(Title).TrimToLen(100);
            entity.Description = StringHelper.EnsureNotNull(Description).TrimToLen(1000);
            entity.Text = StringHelper.EnsureNotNull(Text);
        }

        #endregion
    }

    /// <summary>
    /// Updates the publication translation.
    /// </summary>
    public class UpdatePublicationTranslation : UpdateTranslation
        <TPublicationEntity, PublicationEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("PBLSH");
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .IsVerified()
                    .Rule((ctx, uow) =>
                    {
                        var author = ctx.PublicationAuthor(uow);
                        if(author == null)
                            return false;
                        var translation = uow.Execute(new GetPublicationTranslation
                        {
                            EntityID = EntityID
                        }).Result;
                        if(translation == null)
                            return false;
                        return translation.Holder.Author.EntityID == author.EntityID;
                    });
            }
        }

        /// <summary>
        /// Gets or sets the title.
        /// </summary>
        public string Title
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the description.
        /// </summary>
        public string Description
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the text.
        /// </summary>
        public string Text
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Revise(IUnitOfWork uow, TPublicationEntity entity)
        {
            base.Revise(uow, entity);

            entity.Title = StringHelper.EnsureNotNull(Title).TrimToLen(100);
            entity.Description = StringHelper.EnsureNotNull(Description).TrimToLen(1000);
            entity.Text = StringHelper.EnsureNotNull(Text);
        }

        #endregion
    }

    /// <summary>
    /// Saves a publication translation.
    /// </summary>
    public class SavePublicationTranslation : SaveTranslation
        <TPublicationEntity, PublicationEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("PBLSH");
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .IsVerified()
                    .Rule((ctx, uow) =>
                    {
                        var author = ctx.PublicationAuthor(uow);
                        if(author == null)
                            return false;
                        var pub = uow.Execute(new GetPublication
                        {
                            EntityID = HolderID
                        }).Result;
                        if(pub == null)
                            return false;
                        return pub.Author.EntityID == author.EntityID;
                    });
            }
        }

        /// <summary>
        /// Gets or sets the title.
        /// </summary>
        public string Title
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the description.
        /// </summary>
        public string Description
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the text.
        /// </summary>
        public string Text
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Work(IUnitOfWork uow, out TPublicationEntity result)
        {
            var translation = uow.Execute(new GetPublicationTranslationByLanguage
            {
                HolderID = HolderID,
                LanguageID = LanguageID
            }).Result;
            if(translation == null)
            {
                translation = uow.Execute(new CreatePublicationTranslation
                {
                    HolderID = HolderID,
                    LanguageID = LanguageID,
                    Title = Title,
                    Description = Description,
                    Text = Text
                }).Result;
            }
            else
            {
                translation = uow.Execute(new UpdatePublicationTranslation
                {
                    EntityID = translation.EntityID,
                    LanguageID = LanguageID,
                    Title = Title,
                    Description = Description,
                    Text = Text
                }).Result;
            }
            result = translation;
        }

        #endregion
    }

    /// <summary>
    /// Deletes the publication translation.
    /// </summary>
    public class DeletePublicationTranslation : DeleteTranlsation
        <TPublicationEntity, PublicationEntity>,
        ISecuredOperation, IApiOperation
    {
        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("PBLSH");
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .IsVerified()
                    .Rule((ctx, uow) =>
                    {
                        var author = ctx.PublicationAuthor(uow);
                        if(author == null)
                            return false;
                        var translation = uow.Execute(new GetPublicationTranslation
                        {
                            EntityID = EntityID
                        }).Result;
                        if(translation == null)
                            return false;
                        return translation.Holder.Author.EntityID == author.EntityID;
                    });
            }
        }
    }

    /// <summary>
    /// Gets the publication translation.
    /// </summary>
    public class GetPublicationTranslation : GetTranlsation
        <TPublicationEntity, PublicationEntity>,
        IApiOperation
    {
    }

    /// <summary>
    /// Gets the publication translation.
    /// </summary>
    public class GetPublicationTranslationByLanguage : GetTranlsationByLanguage
        <TPublicationEntity, PublicationEntity>,
        IApiOperation
    {
    }

    #endregion

    #region __Search__

    /// <summary>
    /// Search over publication collection.
    /// </summary>
    public class SearchPublications : SearchOperation<PublicationEntity>,
        IApiOperation
    {
        #region Ctors

        /// <summary>
        /// Initializes a new class instance.
        /// </summary>
        public SearchPublications()
        {
            Term = SearchTerm.Empty;
            SortDir = SortDirection.Ascending;
            SortBy = new []
            {
                PublicationSortBy.ID
            };
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the search term.
        /// </summary>
        public SearchTerm Term
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the language identifier.
        /// </summary>
        public int? LanguageID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the author identifier.
        /// </summary>
        public int? AuthorID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the tag identifier.
        /// </summary>
        public int? TagID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the attribute identifiers.
        /// </summary>
        public int[] AttributeIDs
        {
            get;
            set;
        }

        /// <summary>
        ///   Gets or sets the creation date 'from'.
        /// </summary>
        public DateTime? CreatedFrom
        {
            get;
            set;
        }

        /// <summary>
        ///   Gets or sets the creation date 'to'.
        /// </summary>
        public DateTime? CreatedTo
        {
            get;
            set;
        }

        /// <summary>
        ///   Gets or sets the pulication date 'from'.
        /// </summary>
        public DateTime? PublishedFrom
        {
            get;
            set;
        }

        /// <summary>
        ///   Gets or sets the pulication date 'to'.
        /// </summary>
        public DateTime? PublishedTo
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flag mask.
        /// </summary>
        public PublicationFlags FlagMask
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the sort direction.
        /// </summary>
        public SortDirection SortDir
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the sort by.
        /// </summary>
        public PublicationSortBy[] SortBy
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override IQueryable<PublicationEntity> Build(IUnitOfWork uow, IQueryable<PublicationEntity> query)
        {
            query = base.Build(uow, query);
            query = query.Fetch(x => x.Author).ThenFetch(x => x.Account);
            query = query.FilterByFlags(x => (int)x.Flags, (int)FlagMask);
            query = query.FilterByDateRange(x => x.CreatedOn, CreatedFrom, CreatedTo);
            query = query.FilterByDateRange(x => x.PublishedOn, PublishedFrom, PublishedTo);
            switch(Term.Mode)
            {
                case SearchTerm.SearchMode.StartsWith:
                    if(LanguageID.HasValue)
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Language.EntityID == LanguageID.Value &&
                            i.Title.StartsWith(Term.Keyword)));
                    else
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Title.StartsWith(Term.Keyword)));
                    break;
                case SearchTerm.SearchMode.EndsWith:
                    if(LanguageID.HasValue)
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Language.EntityID == LanguageID.Value &&
                            i.Title.EndsWith(Term.Keyword)));
                    else
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Title.EndsWith(Term.Keyword)));
                    break;
                case SearchTerm.SearchMode.Contains:
                    if(LanguageID.HasValue)
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Language.EntityID == LanguageID.Value &&
                            (i.Title.Contains(Term.Keyword) ||
                            i.Description.Contains(Term.Keyword))));
                    else
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Title.Contains(Term.Keyword) ||
                            i.Description.Contains(Term.Keyword)));
                    break;
                case SearchTerm.SearchMode.Equals:
                    if(LanguageID.HasValue)
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Language.EntityID == LanguageID.Value &&
                            i.Title.Equals(Term.Keyword)));
                    else
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Title.Equals(Term.Keyword)));
                    break;
                default:
                    if(LanguageID.HasValue)
                        query = query.Where(x => x.Translations.Any(i => i.Language.EntityID == LanguageID.Value));
                    break;
            }
            if(TagID.HasValue)
                query = query.Where(x => x.Tags.Any(i => i.EntityID == TagID.Value));
            if(AttributeIDs != null && AttributeIDs.Any())
                query = query.Where(x => x.Attributes.Count(i => AttributeIDs.Contains(i.EntityID)) == AttributeIDs.Count());
            if(AuthorID.HasValue)
                query = query.Where(x => x.Author.EntityID == AuthorID.Value);
            if(SortBy != null)
            {
                for(int i = 0; i < SortBy.Length; i++)
                {
                    switch(SortBy[i])
                    {
                        case PublicationSortBy.Code:
                            query = query.OrderBy(x => x.Code, SortDir, i != 0);
                            break;
                        case PublicationSortBy.RatingCount:
                            query = query.OrderBy(x => x.RatingCount, SortDir, i != 0);
                            break;
                        case PublicationSortBy.CommentCount:
                            query = query.OrderBy(x => x.CommentCount, SortDir, i != 0);
                            break;
                        case PublicationSortBy.RatingAverage:
                            query = query.OrderBy(x => x.RatingAverage, SortDir, i != 0);
                            break;
                        case PublicationSortBy.PublishedOn:
                            query = query.OrderBy(x => x.PublishedOn, SortDir, i != 0);
                            break;
                        case PublicationSortBy.CreatedOn:
                            query = query.OrderBy(x => x.CreatedOn, SortDir, i != 0);
                            break;
                        default:
                            query = query.OrderBy(x => x.EntityID, SortDir, i != 0);
                            break;
                    }
                }
            }
            return query;
        }

        #endregion
    }

    #endregion

    #region __Map__

    /// <summary>
    /// Maps the tag to publication.
    /// </summary>
    public class MapPublicationTagToPublication : MapOperation
        <PublicationEntity, PublicationTagEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("PBLSH");
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .IsVerified()
                    .Rule((ctx, uow) =>
                    {
                        var author = ctx.PublicationAuthor(uow);
                        if(author == null)
                            return false;
                        var publicaiton = uow.Execute(new GetPublication
                        {
                            EntityID = EntityID
                        }).Result;
                        if(publicaiton == null)
                            return false;
                        return publicaiton.Author.EntityID == author.EntityID;
                    });
            }
        }

        #endregion

        #region Utilities

        protected override void Work(IUnitOfWork uow, out PublicationEntity result)
        {
            base.Work(uow, out result);
            uow.Execute(new UpdatePublicationTagStats
            {
                EntityID = ChildID
            });
        }

        #endregion
    }

    /// <summary>
    /// Unmaps the tag from publication.
    /// </summary>
    public class UnmapPublicationTagFromPublication : UnmapOperation
        <PublicationEntity, PublicationTagEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("PBLSH");
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .IsVerified()
                    .Rule((ctx, uow) =>
                    {
                        var author = ctx.PublicationAuthor(uow);
                        if(author == null)
                            return false;
                        var publicaiton = uow.Execute(new GetPublication
                        {
                            EntityID = EntityID
                        }).Result;
                        if(publicaiton == null)
                            return false;
                        return publicaiton.Author.EntityID == author.EntityID;
                    });
            }
        }

        #endregion

        #region Utilities

        protected override void Work(IUnitOfWork uow, out PublicationEntity result)
        {
            base.Work(uow, out result);
            uow.Execute(new UpdatePublicationTagStats
            {
                EntityID = ChildID
            });
        }

        #endregion
    }

    /// <summary>
    /// Maps the attribute to publication.
    /// </summary>
    public class MapLookupAttributeToPublication : MapOperation
        <PublicationEntity, LookupAttributeEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("PBLSH");
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .IsVerified()
                    .Rule((ctx, uow) =>
                    {
                        var author = ctx.PublicationAuthor(uow);
                        if(author == null)
                            return false;
                        var publicaiton = uow.Execute(new GetPublication
                        {
                            EntityID = EntityID
                        }).Result;
                        if(publicaiton == null)
                            return false;
                        return publicaiton.Author.EntityID == author.EntityID;
                    });
            }
        }

        #endregion

        #region Utilities

        /// <summary>
        /// Performs the operation validation.
        /// </summary>
        /// <param name="uow">The unit of work.</param>
        /// <returns>true, whether the operation is allowed to be executed; otherwise false.</returns>
        protected override Err Validate(IUnitOfWork uow)
        {
            var attribute = uow.Execute(new GetLookupAttribute
            {
                EntityID = ChildID,
                ThrowsException = true
            }).Result;
            if(!attribute.Flags.HasFlag(LookupAttributeFlags.Common) &&
                !attribute.Flags.HasFlag(LookupAttributeFlags.Publication))
            {
                return Err.Of(this).NotAllowed();
            }
            return base.Validate(uow);
        }

        #endregion
    }

    /// <summary>
    /// Unmaps the attribute from publication.
    /// </summary>
    public class UnmapLookupAttributeFromPublication : UnmapOperation
        <PublicationEntity, LookupAttributeEntity>,
        ISecuredOperation, IApiOperation
    {
        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("PBLSH");
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .IsVerified()
                    .Rule((ctx, uow) =>
                    {
                        var author = ctx.PublicationAuthor(uow);
                        if(author == null)
                            return false;
                        var publicaiton = uow.Execute(new GetPublication
                        {
                            EntityID = EntityID
                        }).Result;
                        if(publicaiton == null)
                            return false;
                        return publicaiton.Author.EntityID == author.EntityID;
                    });
            }
        }
    }

    #endregion
}
